<template>
  <div class="container">
    <salaryTopTitle
      @gobackTriser="goBack"
      :salaryOperate="salaryOperate"
      :salaryExcel="salaryExcel"
    ></salaryTopTitle>

    <!--制作工资表-->
    <div class="mainCon">
      <createSalaryStep :activeIndex="activeIndex"></createSalaryStep>
      <div class="createPayWin">
        <p>创建工资表</p>
        <el-row class="toolbar" style="padding-bottom: 0">
          <el-form
            :model="formData"
            label-width="85px"
            ref="formData"
            :rules="formRules"
          >
            <el-row class="row-padding-bottom">
              <el-col>
                <el-form-item label="创建方式">
                  <el-input
                    v-model="createWay"
                    disabled="disabled"
                    class="createWay"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="row-padding-bottom">
              <el-col>
                <el-form-item label="企业名称">
                  <el-input
                    v-model="nickName"
                    disabled="disabled"
                    class="companyName"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="row-padding-bottom">
              <el-col>
                <el-form-item label="发薪月份" prop="month">
                  <el-date-picker
                    v-model="formData.month"
                    type="month"
                    value-format="yyyy-MM"
                    placeholder="选择月"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="row-padding-bottom">
              <el-col>
                <el-form-item label="选择文件" prop="excel">
                  <!-- <el-input v-model="input" type="input"></el-input> -->
                  <span class="uploadBox el-input__inner">
                    <!-- <uploadInput ref="uploadInput" :placeholder="placeholder"></uploadInput> -->
                    <form id="salaryExcelForm">
                      <input
                        type="file"
                        id="salaryExcel"
                        name="salaryExcel"
                        placeholder="placeholder"
                        @change="upLoadExcel"
                      />
                      <input
                        type="text"
                        v-model="year"
                        name="year"
                        style="display: none"
                      />
                      <input
                        type="text"
                        v-model="month"
                        name="month"
                        style="display: none"
                      />
                    </form>
                  </span>
                  导入的工资表应与模板格式一致，<el-link
                    type="primary"
                    @click="downLoad('salaryExcel')"
                    >点击下载工资表模板</el-link
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="row-padding-bottom">
              <el-button
                class="commonBut saveBtn"
                @click="toImportSalary"
                :loading="isAdd"
                >导入</el-button
              >
              <el-button class="commonBut" @click="goBack"
                >返回上一页</el-button
              >
              <!-- <div class="goBack" @click="goBack">
               <i class="icon iconfont iconfanhui"></i> 返回上一页
            </div> -->
            </el-row>
          </el-form>
        </el-row>
      </div>
    </div>

    <el-dialog
      title="上传失败"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <div class="errorNoticeBox">
        <i class="icon iconfont iconshibai1"></i>
      </div>
      <div v-html="errorNotice" class="errorBox"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="closeDialog" class="save"
          >确认</el-button
        >
        <el-button @click.native="closeDialog" class="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import common from '../../kits/common'
import createSalaryStep from '@/components/publicCom/createSalaryStepJz'
import salaryTopTitle from '@/components/publicCom/salaryTopTitle'

export default {
  name: 'importSalary',
  components: {
    createSalaryStep,
    salaryTopTitle,
  },
  data() {
    var checkInput = (rule, value, callback) => {
      var that = this
      setTimeout(function () {
        var val = $('#salaryExcel').val()
        if (!val) {
          return callback(new Error('请选择需要导入的工资表'))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      salaryOperate: 'salaryOperate', //非建工资下载
      salaryExcel: 'salaryExcel', //非建工资模板
      createWay: '导入工资表',
      activeIndex: 0,
      comapnyName: '公司名称',
      placeholder: '请选择Excel文件',
      formData: {},
      options: [
        {
          value: '选项1',
          label: '黄金糕',
        },
      ],
      formRules: {
        excel: [
          {
            required: true,
            // pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            // message: "请选择",
            validator: checkInput,
            trigger: 'blur',
          },
        ],
        month: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请选择生成工资表的发薪月份',
            trigger: 'change',
          },
        ],
      },
      year: '',
      month: '',
      formVisible: false,
      errorNotice: '',
      isAdd: false,
      nickName: '',
    }
  },
  created() {
    this.nickName = this.$store.state.nickName
  },
  methods: {
    toImportSalary() {
      this.isAdd = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.year = this.formData.month.split('-')[0] //年
          this.month = this.formData.month.split('-')[1] //月
          var that = this
          var Filedata = $('#salaryExcel').val()

          if (!/\.(xls|xlsx)$/.test(Filedata)) {
            this.$message({
              message: 'excel类型必须是.xls,xlsx中的一种',
              type: 'warning',
            })
            this.isAdd = false
            $('#salaryExcel').val('')
            return
          }

          setTimeout(function () {
            //that.isAdd = true;
            that.uploadFileByAjaxSubmit(
              'api-su/salary/expand/import',
              that.success,
              that.error
            )
          }, 500)
        } else {
          this.isAdd = false
          // this.$refs.detail.validateField('pictureIds')
        }
      })
    },
    upLoadExcel() {
      this.$refs.formData.validateField('excel')
    },
    success(data) {
      this.isAdd = false
      if (!data.hasError) {
        this.$message({
          message: '导入成功',
          type: 'success',
        })
        // this.$router.push({
        //   path:'/home/salary/editSalary/'+data.result.id,
        // })
        // this.createSuccess(data);
        $('#salaryExcel').val('')
        this.formData.month = ''
        this.createSuccess(data.result)
      } else {
        this.errorNotice = data.errorMsg
        this.formVisible = true
        //  this.$alert(data, "上传失败", {
        //   dangerouslyUseHTMLString: true
        // });
      }
    },
    createSuccess(data) {
      // this.$router.push("/home/salary/editSalary"+ data.id);
      this.$router.push({
        path: '/home/salary/editSalary',
        name: 'editSalary',
        query: {
          salaryId: data.id,
          type: 'import',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salary/qySalaryList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    closeDialog() {
      this.formVisible = false
    },
    error(data) {
      this.isAdd = false
      this.$message({
        message: '数据请求失败',
        type: 'warning',
      })
    },
    uploadFileByAjaxSubmit(url, successCallBack, errorCallBack) {
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        dataType: 'json',
        headers: { Authorization: 'Bearer ' + token },
        success: function (data) {
          successCallBack(data)
        },
        error: function () {
          errorCallBack()
        },
        //		resetForm: true
      }
      //	$("#uploadFileForm").ajaxSubmit(options);
      //$(".uploadFileForm").ajaxSubmit(options);
      //$("from").ajaxSubmit(options);
      //三种方式均可
      $('#salaryExcelForm').ajaxSubmit(options)
      // $(dom).ajaxSubmit(options);
      return false
    },
    downLoad(type) {
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/findurl',
        data: {
          name: type,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            window.open(response.data.result.url)
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
        .catch((error) => {})
    },
    goBack() {
      this.$router.push('/home/salary/createSalaryWay')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salary/qySalaryList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  top: 197px;
}

.el-form-item {
  margin-bottom: 28px;
}

.createPayWin {
  margin-top: 60px;
  text-align: center;
  margin-bottom: 0;
  padding-bottom: 70px;
  p {
    font-size: 28px;
    color: #333;
    font-family: '宋体';
    margin-bottom: 60px;
  }
  .el-form {
    display: inline-block;
    width: 460px;
    /deep/ .el-form-item__content {
      width: 340px;
    }
    /deep/ .el-input {
      width: 340px;
    }
    .row-padding-bottom {
      // margin-bottom: 10px;
    }
    .commonBut {
      margin-top: 8px;
    }
    .goBack {
      margin-top: 22px;
      font-size: 14px;
      color: #999;
      cursor: pointer;
      i {
        vertical-align: middle;
      }
    }
    .createWay /deep/ input {
      font-size: 14px;
      color: #666;
      background: #bfc5cc;
      border: 1px solid #bfc5cc;
    }
    .companyName /deep/ input {
      border: none;
      color: #666;
    }
  }
  /deep/ .toolbar {
    padding: 0;
  }
  .uploadBox {
    line-height: 36px;
    width: 100%;
    text-align: left;
    /deep/ form {
      display: inline-block;
    }
  }
}

.errorNoticeBox {
  text-align: center;
  margin-bottom: 24px;
  i {
    color: red;
    font-size: 50px;
  }
}
.errorBox {
  line-height: 24px;
}

.el-link {
  height: 20px;
  line-height: 20px;
}
</style>
